<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>D3交互式数据可视化</title>
</head>
<body>
	<ul>
		<strong>力导向图</strong>
		<li>d3.layout.force()</li>
		<li>force.size([size])</li>
		<li>force.nodes([nodes])</li>
		<li>force.friction([friction])</li>
		<li>force.charge([charge])</li>
		<li>force.chargeDistance([distance])</li>
		<li>force.theta([theta])</li>
	</ul>
	<div class="force">
		
	</div>
	<script src="js/d3_3.5.7.js"></script>
	<script>
		var width = 500;
		var height = 500
		var svg = d3.select(".force").append('svg').attr({"width":width,"height":height});
		var nodes = [{name:"0"},{name:"1"},{name:"2"},{name:"3"},{name:"4"},{name:"5"},{name:"6"}];
		var edges = [{source:0,target:1},{source:0,target:2},{source:0,target:3},{source:1,target:4},{source:1,target:5},{source:1,target:6}];
		
		var force = d3.layout.force()
						.nodes(nodes)
						.links(edges)
						.size([width,height])
						.linkDistance(90)
						.charge(-400)
		
		force.start();
		
//		console.log(nodes)
//		console.log(edges)
		
		var color = d3.scale.category20()
		
		//绘制连线
		var lines = svg.selectAll(".forceLine")
						.data(edges)
						.enter()
						.append("line")
						.attr("class","forceLine")
						.style("stroke","black")
						
		//绘制节点
		var circles = svg.selectAll(".forceCircle")
						.data(nodes)
						.enter()
						.append("circle")
						.attr("class","forceCircle")
						.attr("r",20)
						.style("fill",function(d,i) {
							return color(i);
						})
						.call(force.drag); //允许拖动
		
		//绘制文字
		var texts = svg.selectAll(".forceText")
						.data(nodes)
						.enter()
						.append("text")
						.attr("class","forceText")
						.attr("x",function(d) {
							return d.x;
						})
						.attr("y",function(d) {
							return d.y;
						})
						.attr("dy",".3em")
						.text(function(d) {return d.name})
						
		//tick事件的监听器
		force.on("tick",function() {
			//更新连线的端点坐标
			lines.attr("x1",function(d) {
				return d.source.x;
			})
			lines.attr("y1",function(d) {
				return d.source.y;
			})
			lines.attr("x2",function(d) {
				return d.target.x;
			})
			lines.attr("y2",function(d) {
				return d.target.y;
			})
			//更新节点坐标
			circles.attr("cx",function(d) {
				return d.x;
			})
			circles.attr("cy",function(d) {
				return d.y;
			})
			//更新节点文字坐标
			texts.attr("x",function(d) {
				return d.x;
			})
			texts.attr("y",function(d) {
				return d.y;
			})
		})
		
		
		//力学图运动开始
		force.on("start",function() {
			console.log("运动开始");
		})
		force.on("end",function() {
			console.log("运动结束")
		})
						
		var drag = force.drag()
					.on("dragstart",function(d) {
						d.fixed = true;
					})
					.on("dragend",function(d,i) {
						d3.select(this).style("fill",color(i));
					})
					.on("drag",function(d) {
						d3.select(this).style("fill","yellow")
					})
						
		
	</script>
</body>
</html>